// admin/system/dao/sys_job_log_dao.go
package dao

import (
	"go-admin1/admin/system/model"
	"go-admin1/internal/infrastructure/database"
	"go-admin1/internal/infrastructure/logger"

	"go.uber.org/zap"
	"gorm.io/gorm"
)

// SysJobLogDao 任务日志数据访问接口
type SysJobLogDao interface {
	Create(jobLog *model.SysJobLog) error
	GetByID(id int64) (*model.SysJobLog, error)
	Delete(id int64) error
	List(page, pageSize int) ([]*model.SysJobLog, int64, error)
	CleanAll() error
}

type sysJobLogDao struct {
	db *gorm.DB
}

// NewSysJobLogDao 创建任务日志数据访问实例
func NewSysJobLogDao() SysJobLogDao {
	return &sysJobLogDao{
		db: database.GetDB(),
	}
}

func (j *sysJobLogDao) Create(jobLog *model.SysJobLog) error {
	logger.Info("创建任务日志")
	return j.db.Create(jobLog).Error
}

func (j *sysJobLogDao) GetByID(id int64) (*model.SysJobLog, error) {
	logger.Debug("根据ID获取任务日志", zap.Int64("job_log_id", id))
	var jobLog model.SysJobLog
	err := j.db.Where("job_log_id = ?", id).First(&jobLog).Error
	return &jobLog, err
}

func (j *sysJobLogDao) Delete(id int64) error {
	logger.Info("删除任务日志", zap.Int64("job_log_id", id))
	return j.db.Where("job_log_id = ?", id).Delete(&model.SysJobLog{}).Error
}

func (j *sysJobLogDao) List(page, pageSize int) ([]*model.SysJobLog, int64, error) {
	logger.Debug("获取任务日志列表", zap.Int("page", page), zap.Int("page_size", pageSize))
	var jobLogs []*model.SysJobLog
	var total int64

	offset := (page - 1) * pageSize
	db := j.db.Model(&model.SysJobLog{})

	if err := db.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	if err := db.Offset(offset).Limit(pageSize).Order("create_time DESC").Find(&jobLogs).Error; err != nil {
		return nil, 0, err
	}

	return jobLogs, total, nil
}

func (j *sysJobLogDao) CleanAll() error {
	logger.Info("清空任务日志")
	return j.db.Session(&gorm.Session{AllowGlobalUpdate: true}).Delete(&model.SysJobLog{}).Error
}
